import sys
import traceback
from fastapi_jwt_auth.exceptions import MissingTokenError, JWTDecodeError, InvalidHeaderError
from prisma.errors import UniqueViolationError, MissingRequiredValueError, FieldNotFoundError
from fastapi import Request

from json.decoder import JSONDecodeError

from utils.resp import BusinessException

import psutil

def is_blank(text: str) -> bool:
    return text is None or len(text) == 0 or text.strip() == ''




def find_process_path(process_name) -> list[dict]:
    processes = psutil.process_iter()

    is_all = False
    if is_blank(process_name):
        is_all = True

    list = []
    # 遍历进程列表
    for process in processes:
        path = process.exe()
        pid = process.pid

        if is_all:
            list.append({
                "pid": process.pid,
                "path": process.exe()
            })
        else:
            # 判断进程是否为目标进程
            if process.name() == process_name:
                # 获取目标进程路径
                # path = process.exe()
                # print("process.pid=", process.pid)
                # print("python path=", path)
                list.append({
                    "pid": pid,
                    "path": path
                })

    return list



def process_error(e: Exception):
    print("process_error....", e)
    exc_type, exc_value, exc_traceback = sys.exc_info() 
    print(exc_type)
    print(exc_value)
    
    traceback.print_tb(exc_traceback)
    # traceback.print_exception(exc_type, exc_value, exc_traceback, limit=None, file=sys.stdout)
    

    if isinstance(e, JWTDecodeError) or isinstance(e, InvalidHeaderError):
        # raise BusinessException("JWTDecodeError", "jwt error", 422)
        raise BusinessException("JWTDecodeError", "token 错误", 422)
    
    if isinstance(e, MissingTokenError):
        # raise BusinessException("MissingTokenError", "jwt missing", 401)
        raise BusinessException("MissingTokenError", "token 不存在", 401)
    

    if isinstance(e, UniqueViolationError):
        raise BusinessException("UserError", "数据已存在！", -1)
    
    if isinstance(e, MissingRequiredValueError):
        raise BusinessException("UserError", "字段缺失", -1)

    if isinstance(e, FieldNotFoundError):
        raise BusinessException("UserError", "字段不存在", -1)
    
    
    if isinstance(e, JSONDecodeError):
        raise BusinessException("UserError", f"reqeust body is error", -1)
    

    raise BusinessException("Error", str(e), -1)





class TushanCRUD:


    STATIC_TUSHAN_ADMIN_MAP = {
        
    }

    NOT_WHERE_KEYS = ['_sort', '_order', '_start', '_end']
    
    def __init__(self) -> None:
        pass


    def get_resource(self, resource_id: str):
        if not self.contains(resource_id):
            return None
        
        return TushanCRUD.STATIC_TUSHAN_ADMIN_MAP.get(resource_id)

    def contains(self, resource_id: str):
        if is_blank(resource_id) is None:
            return False
        
        if resource_id not in TushanCRUD.STATIC_TUSHAN_ADMIN_MAP:
           return False
        
        return True



    # prisma.errors.FieldNotFoundError'>
    # Could not find field at `findManyUser.orderBy.username`
    async def listAction(self, prismaAction: any, request: Request):
        # https://jsonplaceholder.typicode.com/users?_end=20&_order=ASC&_sort=username&_start=0
        query_params = request.query_params


        # http://127.0.0.1:8068/api/admin/users?role=5&_sort=id&_order=DESC&_start=0&_end=20
        where = {}
        for key, val in query_params.items():
            if key not in TushanCRUD.NOT_WHERE_KEYS:
                if str(val).isdigit():
                    where[key] = int(val)
                else:
                    where[key] = val

        print(where)
        count = await prismaAction.count(
            where=where
        )

        if count == 0:
            return (0, [])


        sort = query_params.get("_sort") or "id"
        order = query_params.get("_order") or "desc"
        order = order.lower()

        order_by = {}
        order_by[sort] = order
        # print(order_by)
        # new_order_by = {re.sub(r"'([^']*)'", r"\1", key): value for key, value in order_by.items()}
        # new_order_by = {eval(key): value for key, value in order_by.items()}
        # new_order_by = {key.strip("'"): value for key, value in order_by.items()}
        # print(new_order_by)

        page = int(query_params.get("_start")) or 0
        pageSize = int(query_params.get("_end")) or 100


        if page < 0:
            page = 0
        
        if pageSize <=0:
            page = 100

        skip = page * pageSize


        list = await prismaAction.find_many(
            where=where,
            take=pageSize,
            skip=skip,
            order=order_by,
            # order={
            #     'id': "desc",
            # }
        )

        return (count, list)


    # 新增
    async def postAction(self, prismaAction: any, request: Request):
        body = await request.json()

        return await prismaAction.create(
            data=body
        )

    # 修改
    async def putAction(self, prismaAction: any, id: str, request: Request):
        # path_params = request.path_params
        # path_params.get("")
        # print(path_params)

        body = await request.json()

        return await prismaAction.update(
            where={
                'id': int(id),
            },
            data=body
        )
    
    async def deleteAction(self, prismaAction: any, id: str, request: Request):

        # return await prismaAction.update(
        #     where={
        #         'id': int(id),
        #     },

        #     data={
        #         'deleted': 1
        #     }
        # )
    
        return await prismaAction.delete(
            where={
                'id': int(id),
            }
        )


